package org.zoffy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.zoffy.mapper.PopularSiteMapper;
import org.zoffy.model.dto.PopularSiteDTO;
import org.zoffy.model.entity.PopularSite;
import org.zoffy.model.vo.PopularSiteVO;
import org.zoffy.service.PopularSiteService;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class PopularSiteServiceImpl implements PopularSiteService {
    private final PopularSiteMapper popularSiteMapper;
    @Override
    public Long addSite(PopularSiteDTO popularSiteDTO, Long userId) {
        PopularSite popularSite = new PopularSite();
        popularSite.setSiteName(popularSiteDTO.getSiteName());
        popularSite.setSiteUrl(popularSiteDTO.getSiteUrl());
        popularSite.setSitePic(popularSiteDTO.getSitePic());
        popularSite.setUserId(userId);
        popularSiteMapper.insert(popularSite);
        return popularSite.getId();
    }

    @Override
    public Boolean updateSite(Long id, PopularSiteDTO popularSiteDTO, Long userId) {
        LambdaQueryWrapper<PopularSite> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(PopularSite::getId,id)
                .eq(PopularSite::getUserId,userId);

        PopularSite popularSite = popularSiteMapper.selectOne(queryWrapper);
        if (popularSite==null){
            return false;
        }
        popularSite.setId(id);
        popularSite.setSiteName(popularSiteDTO.getSiteName());
        popularSite.setSiteUrl(popularSiteDTO.getSiteUrl());
        popularSite.setSitePic(popularSiteDTO.getSitePic());
        return popularSiteMapper.updateById(popularSite) > 0;
    }

    @Override
    public List<PopularSiteVO> querySites(Long userId) {
        LambdaQueryWrapper<PopularSite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PopularSite::getUserId, userId)
                   .eq(PopularSite::getIsDelete, 0);
                   
        return popularSiteMapper.selectList(queryWrapper).stream()
                .map(site -> {
                    PopularSiteVO vo = new PopularSiteVO();
                    vo.setId(site.getId());
                    vo.setSiteName(site.getSiteName());
                    vo.setSiteUrl(site.getSiteUrl());
                    vo.setSitePic(site.getSitePic());
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public Boolean deleteSite(Long id, Long userId) {
        LambdaQueryWrapper<PopularSite> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(PopularSite::getIsDelete,id)
                .eq(PopularSite::getUserId,userId);

        popularSiteMapper.delete(queryWrapper);
        return true;
    }
}